layui.use('treetable', function () {
    var datas = []; /*[{
        "fileid":0,"name":"公司文件","types":"0","parentId":"1","children":[
            {
                "fileid":1,"name":"子文件1","parentId":"2","children":[]
            },{
                "fileid":2,"name":"子文件2","parentId":"3","children":[]
            },
        ]
    }, {
        "fileid":3,"name":"自建文件","types":"0","parentId":"4","children":[
            {
                "fileid":4,"name":"子文件1","parentId":"5","children":[]
            },{
                "fileid":5,"name":"子文件2","parentId":"6","children":[]
            },
        ]
    }, {
        "fileid":6,"name":"客户目录","parentId":"7","types":"0"
    }, {
        "fileid":7,"name":"垃圾箱","parentId":"8","types":"0"
    }, {
        "fileid":8,"name":"回收箱","parentId":"9","types":"0"
    }] ;*/

    var data1 = [{
        id: "1",
        filename: "layui-logo.jpg",
        url: "statics/images/layui-logo.jpg",
        uploaddate: "2020-10-01"
    }, {id: "2", filename: "layui-logo.jpg", url: "statics/images/layui-logo.jpg", uploaddate: "2020-10-01"}, {
        id: "3",
        filename: "layui-logo.jpg",
        url: "statics/images/layui-logo.jpg",
        uploaddate: "2020-10-01"
    }, {id: "4", filename: "layui-logo.jpg", url: "statics/images/layui-logo.jpg", uploaddate: "2020-10-01"}]

    var treetables = layui.treetable, layer = layui.layer, table = layui.table, $ = layui.jquery, upload = layui.upload,
        form = layui.form, re = "", fileid = "0";
    var fileNames = [];//当前文件目录下所有文件名列表
    //获取树数据
    datas = query();

    //上传列表
    var uploadlist = [];
    var wjCatalogCode = "1"
    //  ispd(wjCatalogCode);
    $("input[name='wjCatalogCode']")[0].value = "公司文件";
    // 渲染表格
    re = treetables.render({
        elem: '#flestree',
        data: datas,
        toolbar: "#flestreetoolbar",
        id: "flestreeid",
        tree: {
            iconIndex: 1,           // 折叠图标显示在第几列
            isPidData: false,        // 是否是id、pid形式数据
            idName: 'fileid',  // id字段名称
        },
        page: false,
        //treeLinkage: true,      //父级展开时是否自动展开所有子级
        cols: [[
            {type: "checkbox", fixed: true},
            {title: "文件目录", field: "name", fixed: true},
            {title: "操作", templet: "#flestreeeditor", width: 120, align: 'center'}
        ]]
    })
    //搜索
    $('#search').click(function () {
        re.filterData($("#treename").val());
    });
    // 监听行单击事件
    treetables.on('row(flestree)', function (obj) {
        fileNames = [];
        wjCatalogCode = obj.data.code;

        // ispd(wjCatalogCode);

        $("input[name='wjCatalogCode']")[0].value = obj.data.name;
        //判断是否有选中的列，有则取消换现点击列
        var selecteds = $(".selecteds");
        if (typeof (selecteds[0]) != "undefined") {
            selecteds.removeClass("selecteds");
        }
        obj.tr[0].classList.add("selecteds");
        re.expand(obj.data.fileid);  // 展开指定节点
        $('#flesttype').val(obj.data.name);
        fileid = obj.data.fileid;
        //刷新文件表
        table.reload('flestableid', {
           // data: data1,
             type: "get"
            , url: "wjinfo/selectByPage"
            ,
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                "wjCatalogCode": wjCatalogCode,//$("input[name='wjCatalogCode']")[0].value,
                "name": ""//$("input[name='name']")[0].value
            }
        }, 'data');
     //   console.log(obj.data) //得到当前行数据
    });
//树新增、删除
    treetables.on('toolbar(flestree)', function (obj) {
        var checkStatus = re.checkStatus(false);  // 获取选中数据，不要半选状态
        switch (obj.event) {
            case 'newuser':
                parent.intab("views/jsp/BasicData/tpl/newupfiles.jsp", "新增公司文件目录")
                break;
            case 'deluser':
                /* if(checkStatus.length!=0){
                     layer.confirm('真的要删除选择的目录么', function (index) {
                         //checkStatus为需要删除的数据
                         layer.msg("删除成功", {icon: 6});
                         layer.close(index);
                     });
                 }else{
                     layer.msg("请选择要删除的目录");
                 }
                 break;*/
                var ids = [];
                if (checkStatus.length == 0) {
                    layer.msg("请选择要删除的节点", {icon: 6});
                    break;
                }
                for (var i = 0; i < checkStatus.length; i++) {
                    ids.push(checkStatus[i].fileid);
                }
                if (deltree(ids)) {
                    layer.msg("删除成功", {icon: 6});
                    /* refrash();*/
                } else {
                    layer.msg("删除失败", {icon: 6});
                }

                break;
        }
        return false;
    });
//树修改、单条删除
    treetables.on('tool(flestree)', function (obj) {
        var data = obj.data;  // 获得当前行数据
        var event = obj.event; // 获得lay-event对应的值
        if (event === 'editor') {
            window.sessionStorage.setItem("wjMidifyData", JSON.stringify(data));
            parent.intab("views/jsp/BasicData/tpl/newupfiles.jsp?id=" + data.fileid, "修改文件目录")
        } else if (event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                if (delpaths(data.path)) {
                    obj.del(); // 删除对应行，并更新缓存
                    layer.msg("删除成功", {icon: 6});
                } else {
                    layer.msg("删除失败", {icon: 6});
                }

                layer.close(index);

                /*obj.del(); // 删除对应行，并更新缓存
                layer.msg("删除成功", {icon: 6});
                layer.close(index);*/
            });
        }
    });


    //文件表格
    table.render({
        elem: '#flesid'
        //, data: data1
        , type: "get"
        , url: "wjinfo/selectByPage"
        , where: {
            "wjCatalogCode": $("input[name='wjCatalogCode']")[0].value,
            "name": $("input[name='name']")[0].value
        }
        , toolbar: '#flestoolbar'
        , cols: [[
            {type: "checkbox", fixed: true}
            , {field: 'name', title: '文件名', fixed: true, event: "wjname"}
            , {field: 'utime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#fleseditor', title: '操作'}
        ]]
        , id: 'flestableid'
        , height: $(document).height() - $('#flesid').offset().top - 50
        , page: true
    });

    //监听提交
    form.on('submit(form-search)', function (data) {
        /* data.field.fileid = fileid;
         layer.msg(JSON.stringify(data.field));*/
        table.reload('flestableid', {
            type: "get"
            , url: "wjinfo/selectByPage"
            , where: {
                "wjCatalogCode": $("input[name='wjCatalogCode']")[0].value,
                "name": $("input[name='name']")[0].value
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }

        }, 'data');
        return false;
    });
//上传
    upload.render({
        elem: '#uploadfile'
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        , data: {"fileType": "wj"}//头像

        /*, url: 'https://httpbin.org/post' //改成您自己的上传接口
        , accept: 'file'*/
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var newfilename = "";
                if (ispd(wjCatalogCode, file.name)) {
                   // newfilename = getFileName(file.name);
                   // layer.msg("此目录下已存在重名的文件，已自动对本文件进行了重命名！");
                    layer.confirm('已存在同名的文件，是否覆盖？', function (index) {

                         layer.close(index);

                     });
                }
                if (newfilename != "") {
                    var obj = {};
                    obj.code = index;
                    obj.name = newfilename;
                    uploadlist.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + newfilename + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var uploadListIns = [];
                        for (var i = 0; i < uploadlist.length; i++) {
                            if (index != uploadlist[i].code) {
                                uploadListIns.push(uploadlist[i]);
                            }
                        }
                        uploadlist = uploadListIns;
                    });

                    $("#uploadlist").append(tr);
                }else{
                    var obj = {};
                    obj.code = index;
                    obj.name = file.name;
                    uploadlist.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var uploadListIns = [];
                        for (var i = 0; i < uploadlist.length; i++) {
                            if (index != uploadlist[i].code) {
                                uploadListIns.push(uploadlist[i]);
                            }
                        }
                        uploadlist = uploadListIns;
                    });

                    $("#uploadlist").append(tr);
                }
            });
        }
        , done: function (res, index, upload) {

            var filename = "";
            for (var i = 0; i < uploadlist.length; i++) {
                if (uploadlist[i].code == index) {
                    filename = uploadlist[i].name;
                    break;
                }
            }
            if (res.data.length > 0) {
                var files = res.data;
                var filepaths = [];
                for (var i = 0; i < files.length; i++) {
                    var obj = {};
                    obj.fileName = files[i].fileName;
                    obj.ftpPath = files[i].ftpPath;
                    filepaths.push(obj);
                }
                if (savefile(filepaths, filename, wjCatalogCode)) {
                    //refrash();
                    table.reload('flestableid', {
                        type: "get"
                        , url: "wjinfo/selectByPage"
                        , where: {
                            "wjCatalogCode": $("input[name='wjCatalogCode']")[0].value,
                            "name": $("input[name='name']")[0].value
                        }
                        , page: {
                            curr: 1 //重新从第 1 页开始
                        }

                    }, 'data');
                }

                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件

            }
            /* if (res.files.file) { //上传成功
                 var tr = $("#uploadlist").find('tr#upload-' + index)
                     , tds = tr.children();
                 tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                 tds.eq(3).html(''); //清空操作
                 return delete this.files[index]; //删除文件队列已经上传成功的文件
             }*/
            this.error(index, upload);
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #ff5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(flestable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        /* table.reload('flestableid', {where: {
                                 fileid: fileid
                             }}); //点击关闭刷新表格*/
                    }
                });
                break;
            case 'restorefile':
                var data = checkStatus.data;
                if (data.length != 0) {
                    layer.confirm('真的恢复选中文件么', function (index) {
                        var ids = [];
                        for (var i = 0; i < data.length; i++) {
                            ids.push(data[i].id);
                        }
                        if (hf(ids)) {
                            refrash();
                            layer.msg("恢复成功", {icon: 6});
                            layer.close(index);

                        } else {
                            layer.msg("恢复失败", {icon: 6});
                        }

                        /*table.reload('flestableid', {where: {
                                fileid: fileid
                            }}); //ajax恢复成功之后刷新表格*/
                    });
                } else {
                    layer.msg("请选择要恢复的文件");
                }
                break;
            case 'deluser'://下载
                var data = checkStatus.data;
                if (data.length != 0) {
                    for (var i = 0; i < data.length; i++) {
                        var filepath =data[i];// data[i].path;
                       // downloadfile(filepath);
                    //<a href ="javascript:void(0)" onclick="downLoad('ip地址:端口号:账号:密码:./home/ftp/测试.doc')">下载</a>
                        downLoad(filepath);
                        /*var a = document.createElement('a');
                        var event = new MouseEvent('click');
                        a.download = data[i].path;
                        a.href = data[i].url;
                        a.dispatchEvent(event)*/
                    }
                } else {
                    layer.msg("请选择要下载的文件");
                }
                break;
        }
    });
    //删除
    table.on('tool(flestable)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                //需要删除的ID：data.id
                if (delByid(data.id)) {
                    layer.msg("删除成功", {icon: 6});
                    obj.del();
                    layer.close(index);
                } else {
                    layer.msg("删除失败", {icon: 6});
                }
                /* obj.del();
                 layer.msg("删除成功", {icon: 6});
                 layer.close(index);
                 table.reload('flestableid', {where: {
                         fileid: fileid
                     }}); //ajax删除成功之后刷新表格*/
            });
        }
        if(obj.event==='wjname'){
            onLineFile(data.path);
        }
    });
});

function query() {
    var obj = [];
    $.ajax({
        type: 'get',
        //  url : 'resource/getTree',
        // data:{"ids":JSON.stringify(distributionid),"saleman":data.field.customersalesman},
        url: 'wjcatalog/select',
        dataType: "json",
        /*  contentType: 'application/json',*/
        async: false,
        success: function (da) {
            if (da.status == 200) {
                obj = getdatas(da.data.children);

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return obj;
}

function getdatas(da) {
    var objs = [];
    for (var i = 0; i < da.length; i++) {
        var obj = {};
        obj.fileid = da[i].id;
        obj.name = da[i].name;
        obj.type = "";
        obj.parentId = da[i].pid;
        obj.path = da[i].path;
        obj.remark = da[i].remark;
        obj.code = da[i].code
        if (da[i].children.length != 0) {
            obj.children = getdatas(da[i].children);
        }

        objs.push(obj);
    }
    return objs;
}

//树添加删除
function deltree(ids) {
    var tf = false;
    $.ajax({
        type: 'post',
        //  url : 'resource/getTree',
        data: {"ids": JSON.stringify(ids)},
        url: 'wjcatalog/delete',
        dataType: "json",
        /*
                     contentType: 'application/json',
        */
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

//根据path删除
function delpaths(path) {
    var tf = false;
    $.ajax({
        type: 'post',
        //  url : 'resource/getTree',
        data: {"path": path},
        url: 'wjcatalog/deleteByPath',
        dataType: "json",
        /*
                     contentType: 'application/json',
        */
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

function delByid(id) {
    var tf = false;
    $.ajax({
        type: 'post',
        //  url : 'resource/getTree',
        data: {"id": id},
        url: 'wjinfo/delByid',
        dataType: "json",
        /*
                     contentType: 'application/json',
        */
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

//恢复
function hf(ids) {
    var tf = false;
    $.ajax({
        type: 'post',
        //  url : 'resource/getTree',
        data: {"ids": JSON.stringify(ids)},
        url: 'wjinfo/hf',
        dataType: "json",
        /*
                     contentType: 'application/json',
        */
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

function refrash() {
    table.reload('flestableid', {
        type: "get"
        , url: "wjinfo/selectByPage"
        , where: {
            "wjCatalogCode": $("input[name='wjCatalogCode']")[0].value,
            "name": $("input[name='name']")[0].value
        }
        , page: {
            curr: 1 //重新从第 1 页开始
        }

    }, 'data');
}

//保存上传的文件
function savefile(filepaths, filename, wjCatalogCode) {
    var tf = false;
    $.ajax({
        type: 'post',
        //  url : 'resource/getTree',    "wjCatalogCode":$("input[name='wjCatalogCode']")[0].value,
        data: {
            "files": JSON.stringify(filepaths), "wjCatalogCode": JSON.stringify(wjCatalogCode),
            "name": JSON.stringify(filename)
        },
        url: 'wjinfo/savefile',
        dataType: "json",
        /*
                     contentType: 'application/json',
        */
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

function downloadfile(path) {
    var tf = false;
    $.ajax({
        type: 'post',
        //  url : 'resource/getTree',    "wjCatalogCode":$("input[name='wjCatalogCode']")[0].value,
        data: {
            "path": JSON.stringify(path)
        },
        url: 'wjinfo/downloadfile',
        dataType: "json",
        /*
                     contentType: 'application/json',
        */
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

/**
 * 获取文件目录下所有的文件名
 * @param wjCatalogCode
 * @returns {[]}
 */
function ispd(wjCatalogCode, filename) {
    /* fileNames=[];*/
    var cun = false;
    $.ajax({
        type: 'get',
        //  url : 'resource/getTree',
        data: {"wjCatalogCode": wjCatalogCode, "name": filename},
        url: 'wjinfo/ispd',
        dataType: "json",
        /*  contentType: 'application/json',*/
        async: false,
        success: function (da) {
            if (da.status == 200) {
                cun = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return cun;
    // return obj;
}

function getFileName(filename) {
    /* fileNames=[];*/
    var cun = "";
    $.ajax({
        type: 'get',
        //  url : 'resource/getTree',
        data: {"filename": filename},
        url: 'wjinfo/getFileName',
        dataType: "json",
        /*  contentType: 'application/json',*/
        async: false,
        success: function (da) {
            if (da.status == 200) {
                cun = da.data;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return cun;
    // return obj;
}

//判断文件名是否重复
function iscf(filename) {
    var tf = false;
    for (var i = 0; i < fileNames.length; i++) {
        if (filename == fileNames[i]) {
            tf = true;
            break;
        }
    }
    return tf;
}
//<a href ="javascript:void(0)" onclick="downLoad('ip地址:端口号:账号:密码:./home/ftp/测试.doc')">下载</a>
function downLoad( param2) {
  /* onLineFile(param2);
    return false;
*/
    window.sessionStorage.setItem("fileName",param2.name);
    var xhr = new XMLHttpRequest();
    var url = "wjinfo/downloadfile2?filename=" + param2.path;
    xhr.open('GET', url, true);
    xhr.responseType = "blob";
    xhr.send(null);

    xhr.onload = function() {
        var aName= window.sessionStorage.getItem("fileName")
       // var aName = xhr.getResponseHeader('Content-Disposition').split('=')[1];

        const data = xhr.response;
        const a = document.createElement('a');
        const blob = new Blob([data],{ type: 'application/force-download' });
        const blobUrl = window.URL.createObjectURL(blob);
        download2(blobUrl,aName) ;
    }
}
function download2(blobUrl,aName){
    const a = document.createElement('a');

    a.style.display = 'none';
    a.download = decodeURIComponent(aName);
    a.href = blobUrl;
    a.click();
   // document.body.removeChild(a);

}